import pandas as pd
import numpy as np

# 一、创建 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
data = [['Google', 10], ['Runoob', 12], ['Wiki', 13]]

# 创建DataFrame
df = pd.DataFrame(data, columns=['Site', 'Age'])

# 使用astype方法设置每列的数据类型
df['Site'] = df['Site'].astype(str)
df['Age'] = df['Age'].astype(float)
print(df)

data = {'Site': ['Google', 'Runoob', 'Wiki'], 'Age': [10, 12, 13]}
df = pd.DataFrame(data)
print(df)

# 创建一个包含网站和年龄的二维ndarray
ndarray_data = np.array([
    ['Google', 10],
    ['Runoob', 12],
    ['Wiki', 13]
])
# 使用DataFrame构造函数创建数据帧
df = pd.DataFrame(ndarray_data, columns=['Site', 'Age'])

# 打印数据帧
print(df)

# 使用字典创建
data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print(df)

data = {
    "calories": [420, 380, 390],
    "duration": [50, 40, 45]
}

# 数据载入到 DataFrame 对象
df = pd.DataFrame(data)

# 返回第一行
print(df.loc[0])
# 返回第二行
print(df.loc[1])
# 返回第一行和第二行
print(df.loc[[0, 1]])

# 自定义 index
data = {
    "calories": [420, 380, 390],
    "duration": [50, 40, 45]
}
df = pd.DataFrame(data, index=["day1", "day2", "day3"])
print(df)
print(df.loc["day2"])

# 二、基本操作 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

data = {
    "Name": [420, 380, 390],
    "Age": [50, 40, 45]
}
df = pd.DataFrame(data, index=[0, 1, 2])
print(pd)

# 获取列
name_column = df['Name']
print("获取列: ")
print(name_column)

# 获取行
first_row = df.loc[0]
print("获取行: ")
print(first_row)

# 选择多列
subset = df[['Name', 'Age']]
print("选择多列: ")
print(subset)

# 过滤行
filtered_rows = df[df['Age'] > 30]
print("过滤行: ")
print(filtered_rows)

# 三、属性和方法 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# 获取列名
columns = df.columns
print("获取列名: ")
print(columns)

# 获取形状（行数和列数）
shape = df.shape
print("获取形状: ")
print(shape)

# 获取索引
index = df.index
print("获取索引: ")
print(index)

# 获取描述统计信息
stats = df.describe()
print("获取描述统计信息: ")
print(stats)

# 四、数据操作 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# 添加新列
df['Salary'] = [50000, 60000, 70000]
print("添加新列: ")
print(df)

# 删除列
df['City'] = ['New York', 'Los Angeles', 'Chicago']
df.drop('City', axis=1, inplace=True)
print("删除列: ")
print(df)

# 排序 根据年龄倒序排序
df.sort_values(by='Age', ascending=False, inplace=True)
print("根据年龄倒序排序: ")
print(df)

# 重命名列
df.rename(columns={'Name': 'Full Name'}, inplace=True)
print("重命名列: ")
print(df)

# 五、从外部数据源创建 DataFrame ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# 从CSV文件创建 DataFrame
# df_csv = pd.read_csv('xxx.csv')

# 从Excel文件创建 DataFrame
# df_excel = pd.read_excel('xxx.xlsx')

# 从字典列表创建 DataFrame
data_list = [{'Name': 'Alice', 'Age': 25}, {'Name': 'Bob', 'Age': 30}]
df_from_list = pd.DataFrame(data_list)
print("从字典列表创建 DataFrame: ")
print(df_from_list)
